import React, { useState, useCallback, useEffect } from 'react';
import { Layout, Typography, message, Spin, ConfigProvider, theme } from 'antd';
import './App.css';
import ImageUploader from './components/ImageUploader';
import StyleSelector from './components/StyleSelector';
import TextPrompt from './components/TextPrompt';
import ImageResult from './components/ImageResult';
import Header from './components/Header';
import { generateStyledImage } from './services/aiService';

const { Content } = Layout;
const { Title } = Typography;

// 自定义主题配置
const themeConfig = {
  algorithm: theme.darkAlgorithm,
  token: {
    colorPrimary: '#6366f1',
    colorInfo: '#6366f1',
    colorSuccess: '#10b981',
    colorWarning: '#f59e0b',
    colorError: '#ef4444',
    borderRadius: 8,
    wireframe: false,
    fontFamily: "'Inter', sans-serif",
  },
};

function App() {
  const [uploadedImage, setUploadedImage] = useState(null);
  const [selectedStyle, setSelectedStyle] = useState('none');
  const [textPrompt, setTextPrompt] = useState('');
  const [resultImage, setResultImage] = useState(null);
  const [isGenerating, setIsGenerating] = useState(false);
  const [generationProgress, setGenerationProgress] = useState(0);
  const [error, setError] = useState(null);
  const [appReady, setAppReady] = useState(false);

  // 应用加载动画
  useEffect(() => {
    const timer = setTimeout(() => {
      setAppReady(true);
    }, 500);
    return () => clearTimeout(timer);
  }, []);

  // 创建全局消息通知样式
  useEffect(() => {
    message.config({
      top: 80,
      duration: 3,
      maxCount: 3,
    });
  }, []);

  // 优化：根据风格选择自动提供文本建议
  useEffect(() => {
    if (selectedStyle !== 'none' && selectedStyle !== 'custom' && textPrompt === '') {
      const styleSuggestions = {
        miyazaki: '宫崎骏风格的梦幻场景，充满想象力和童趣',
        lego: '乐高积木风格，色彩鲜明，块状结构清晰',
        pixar: '皮克斯3D动画风格，光滑细腻的渲染效果',
        shinkai: '新海诚风格，细腻光影和梦幻色彩，唯美浪漫',
        disney: '迪士尼动画风格，充满童话感和快乐氛围'
      };
      
      setTextPrompt(styleSuggestions[selectedStyle] || '');
    }
  }, [selectedStyle]);

  // 模拟进度条更新
  const simulateProgress = useCallback(() => {
    const calculateNextProgress = (current) => {
      if (current >= 95) return 95;
      
      // 在不同阶段使用不同的增长速度
      if (current < 30) return current + Math.random() * 5 + 3;
      if (current < 60) return current + Math.random() * 3 + 2;
      if (current < 85) return current + Math.random() * 2 + 1;
      return current + Math.random() * 1 + 0.5;
    };

    const interval = setInterval(() => {
      setGenerationProgress(prev => {
        const next = calculateNextProgress(prev);
        return Math.min(95, next);
      });
    }, 300);

    return interval;
  }, []);

  // 图像生成函数
  const generateImage = useCallback(async () => {
    // 验证输入
    if (!uploadedImage) {
      message.error('请先上传图片');
      return;
    }

    if (selectedStyle === 'custom' && !textPrompt.trim()) {
      message.warning('使用自定义风格时，请提供文字描述');
      return;
    }

    setError(null);
    setIsGenerating(true);
    setGenerationProgress(0);

    // 启动进度条动画
    const progressInterval = simulateProgress();

    try {
      // 调用AI服务生成图像
      const generatedImageUrl = await generateStyledImage(
        uploadedImage,
        textPrompt,
        selectedStyle
      );
      
      // 设置进度为100%
      clearInterval(progressInterval);
      setGenerationProgress(100);
      
      // 设置结果图像
      setResultImage(generatedImageUrl);
      
      message.success({
        content: '图像生成成功！',
        icon: <span role="img" aria-label="success">✨</span>
      });
    } catch (err) {
      clearInterval(progressInterval);
      setError(err.message || '图像生成失败，请重试');
      message.error({
        content: err.message || '图像生成失败，请重试',
        icon: <span role="img" aria-label="error">❌</span>
      });
    } finally {
      setIsGenerating(false);
    }
  }, [uploadedImage, selectedStyle, textPrompt, simulateProgress]);

  // 处理重置功能
  const handleReset = useCallback(() => {
    setUploadedImage(null);
    setSelectedStyle('none');
    setTextPrompt('');
    setResultImage(null);
    setError(null);
    message.info('已重置所有设置');
  }, []);

  if (!appReady) {
    return (
      <div className="app-loading">
        <Spin size="large" />
        <p>加载中...</p>
      </div>
    );
  }

  return (
    <ConfigProvider theme={themeConfig}>
      <Layout className="app-layout">
        <Header onReset={handleReset} />
        
        <Content className="app-content">
          <div className="main-container">
            <div className="left-panel">
              <ImageUploader 
                onImageUpload={setUploadedImage} 
                disabled={isGenerating}
                currentImage={uploadedImage}
              />
            </div>
            
            <div className="right-panel">
              <StyleSelector 
                selectedStyle={selectedStyle} 
                onStyleSelect={setSelectedStyle}
                disabled={isGenerating || !uploadedImage}
              />
              
              <TextPrompt 
                value={textPrompt} 
                onChange={setTextPrompt} 
                onGenerate={generateImage}
                isGenerating={isGenerating}
                disabled={!uploadedImage || isGenerating}
              />
              
              <ImageResult 
                resultImage={resultImage} 
                isGenerating={isGenerating}
                progress={generationProgress}
                error={error}
                onRetry={generateImage}
              />
            </div>
          </div>
        </Content>
      </Layout>
    </ConfigProvider>
  );
}

export default App;